<template>
  <div>
    <!-- toolbar -->
    <div class="toolbar" ref="buttonBar">
      <div class="left-buttons">
        <slot name="toolbar">
          <div class="bar"></div>
        </slot>
      </div>
      <slot name="tool" v-if="true">
        <div class="tool">
          <el-button-group class="ml-4">
            <el-button type="success"><yu-icon iconName="shaixuan" /> </el-button>
            <el-button @click="exportBtn" type="success"><yu-icon iconName="a-fenxiangdaochulianjie" /></el-button>
            <el-button @click="printContent" type="success"><yu-icon iconName="dayinji" /></el-button>
          </el-button-group>
        </div>
      </slot>
    </div>
    <!-- table主信息必有 -->
    <div>
      <el-table
        id="yu-table"
        v-loading="loading"
        @select="select"
        @select-all="selectAll"
        @selection-change="selectionChange"
        @cell-mouse-enter="cellMouseEnter"
        @cell-mouse-leave="cellMouseLeave"
        @cell-click="cellClick"
        @cell-dblclick="cellDbclick"
        @cell-contextmenu="cellContextmenu"
        @row-click="rowClick"
        @row-dblclick="rowDbclick"
        @row-contextmenu="rowContextmenu"
        @header-click="headerClick"
        @header-contextmenu="headerContextmenu"
        @sort-change="sortChange"
        @filter-change="filterChange"
        @current-change="currentChange"
        @header-dragend="headerDragend"
        @expand-change="expandChange"
        @delete-row="deleteRow"
        @delete-rows="deleteRows"
        :height="tableArrts.height || yuTable.tableArrts.height"
        :max-height="tableArrts.maxHeight || yuTable.tableArrts.maxHeight"
        :stripe="tableArrts.stripe || yuTable.tableArrts.stripe"
        :border="tableArrts.border || yuTable.tableArrts.border"
        :size="tableArrts.size || yuTable.tableArrts.size"
        :fit="tableArrts.fit || yuTable.tableArrts.fit"
        :show-header="tableArrts.showHeader || yuTable.tableArrts.showHeader"
        :highlight-current-row="tableArrts.highlight || yuTable.tableArrts.highlight"
        :empty-text="tableArrts.emptyText || yuTable.tableArrts.emptyText"
        :default-expand-all="tableArrts.defaultExpandAll || yuTable.tableArrts.defaultExpandAll"
        :expand-row-keys="tableArrts.expandRowKeys || yuTable.tableArrts.expandRowKeys"
        :default-sort="tableArrts.defaultSort || yuTable.tableArrts.defaultSort"
        :tooltip-effect="tableArrts.tooltipEffect || yuTable.tableArrts.tooltipEffect"
        :show-summary="tableArrts.showSummary || yuTable.tableArrts.showSummary"
        :sum-text="tableArrts.sumText || yuTable.tableArrts.sumText"
        :select-on-indeterminate="tableArrts.selectOnIndeterminate || yuTable.tableArrts.selectOnIndeterminate"
        :indent="tableArrts.indent || yuTable.tableArrts.indent"
        :lazy="tableArrts.lazy || yuTable.tableArrts.lazy"
        :tree-props="tableArrts.treeProps || yuTable.tableArrts.treeProps"
        :row-key="tableArrts.rowKey || yuTable.tableArrts.rowKey"
        :table-layout="tableArrts.tableLayout || yuTable.tableArrts.tableLayout"
        :scrollbar-always-on="tableArrts.scrollbarAlwaysOn || yuTable.tableArrts.scrollbarAlwaysOn"
        :header-cell-style="tableArrts.headerCellStyle || yuTable.headerCellStyle"
        :row-class-name="rowClassName"
        :row-style="tableArrts.rowStyle || yuTable.rowStyle"
        :cell-class-name="tableArrts.rowStyle"
        :cell-style="tableArrts.rowStyle"
        :header-row-class-name="tableArrts.headerRowClassName"
        :header-row-style="tableArrts.headerRowStyle"
        :header-cell-class-name="tableArrts.headerCellClassName"
        :summary-method="tableArrts.summaryMethod"
        :span-method="tableArrts.spanMethod"
        :load="tableArrts.load"
        :data="tableArrts.haspage ? tableData.data.slice((currentPage - 1) * pagesize, currentPage * pagesize) : tableData.data">
        <el-table-column label="序号" type="index" width="50" align="center" v-if="false"> </el-table-column>

        <template v-for="column in columns" :key="column.key">
          <!-- 选择框 -->
          <template v-if="column.type == 'selection'">
            <el-table-column type="selection" width="40" align="center" :fixed="column.fixed || columnStyle.fixed"> </el-table-column>
          </template>
          <template v-else-if="column.type == 'index'">
            <el-table-column prop="rowIndex" label="NO" width="60" v-if="true" :fixed="column.fixed || columnStyle.fixed" />
          </template>
          <!-- 特殊操作列-->
          <template v-else-if="column.slot">
            <el-table-column
              :label="column.title"
              :fixed="column.fixed || columnStyle.fixed"
              :align="column.align || columnStyle.align"
              :width="column.width || columnStyle.width"
              :show-overflow-tooltip="column.tooltip || columnStyle.tooltip"
              :resizable="column.resizable || columnStyle.resizable"
              :header-align="column.headerAlign || columnStyle.headerAlign">
              <!-- 右侧操作  额外插槽-->
              <template #default="scope">
                <slot :name="column.slot" :scopeData="scope"></slot>
              </template>
            </el-table-column>
          </template>

          <!-- 普通列 -->
          <template v-else>
            <el-table-column
              :prop="column.key"
              :label="column.title"
              :fixed="column.fixed || columnStyle.fixed"
              :align="column.align || columnStyle.align"
              :width="column.width || columnStyle.width"
              :show-overflow-tooltip="column.tooltip || columnStyle.tooltip"
              :resizable="column.resizable || columnStyle.resizable"
              :header-align="column.headerAlign || columnStyle.headerAlign">
              <!--   额外插槽-->
              <template #default="scope" v-if="column.edit">
                <div v-show="scope.row[column.key + 'edit']">
                  <el-input type="text" v-model="scope.row[column.key]" @blur="scope.row[column.key + 'edit'] = false"></el-input>
                </div>
                <div v-show="!scope.row[column.key + 'edit']">
                  {{ scope.row[column.key] }}
                </div>
              </template>
            </el-table-column>
          </template>
        </template>
      </el-table>
    </div>
    <!-- 分页信息-->
    <div class="pageInfo" v-if="tableArrts.haspage">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :hide-on-single-page="pageInfo.hideOnSinglePage || yuTable.pageInfo.hideOnSinglePage"
        :current-page="currentPage"
        :page-sizes="pageInfo.pageSizes || yuTable.pageInfo.pageSizes"
        :page-size="pagesize"
        :pager-count="pageInfo.pagerCount || yuTable.pageInfo.pagerCount"
        :layout="pageInfo.layout || yuTable.pageInfo.layout"
        :total="tableData.data.length"
        :background="yuTable.pageInfo.background"
        :small="yuTable.pageInfo.small">
      </el-pagination>
    </div>
    <ex-excel :exportInfo="exportInfo"></ex-excel>
  </div>
</template>

<script setup>
  import { ArrowLeft, ArrowRight, Delete, Edit, Share, Filter, Printer, FolderOpened } from '@element-plus/icons-vue';
  import '@/assets/style/yu-table.scss';
  import yuTable from '@/pub/yu-table.js';
  import exportExcel from '@/pub/export-excel.js';
  import * as XLSX from 'xlsx/xlsx.mjs';
  import ExExcel from '@/components/com/ExportExcel.vue';

  import { ref, getCurrentInstance, reactive, onMounted, toRef, toRefs, onUpdated } from 'vue';
  const buttonBar = ref(null);
  const props = defineProps({
    tableData: {
      type: Object,
      default: () => {
        return {
          columns: [],
          data: [],
          pageInfo: {},
          tableArrts: {},
        };
      },
    },
    columns: {
      type: Array,
      default: () => {
        return [];
      },
    },
  });
  const selectRows = ref([]);
  const tableData = toRef(props, 'tableData');
  const columns = toRef(props, 'columns');
  //const columns = ref(tableData.value.columns);
  // const data = ref(tableData.value.data)
  const pageInfo = tableData.value.pageInfo || yuTable.pageInfo;
  const tableArrts = tableData.value.tableArrts || yuTable.tableArrts;
  const columnStyle = yuTable.column;
  const currentPage = ref(pageInfo.currentPage || yuTable.pageInfo.currentPage);
  const pagesize = ref(pageInfo.pageSize || yuTable.pageInfo.pagesize);
  const exportInfo = ref({ isShow: false });
  const emit = defineEmits([
    'select',
    'selectAll',
    'selectionChange',
    'cellMouseEnter',
    'cellMouseLeave',
    'cellClick',
    'cellDbclick',
    'cellContextmenu',
    'rowClick',
    'rowDbclick',
    'rowContextmenu',
    'headerClick',
    'headerContextmenu',
    'sortChange',
    'filterChange',
    'currentChange',
    'headerDragend',
    'expandChange',
  ]);

  onMounted(() => {
    changeStyle();
  });
  const changeStyle = () => {
    // console.log(buttonBar.value);
    //debugger;
  };
  // 导出方法
  const exportBtn = () => {
    let expage = {
      currentPage: currentPage.value,
      total: tableData.value.data.length,
      pagesize: pagesize.value,
    };
    exportInfo.value.isShow = true;
    exportInfo.value.tableData = tableData.value;
    exportInfo.value.expage = expage;
  };

  const rowClassName = ({ row, rowIndex }) => {
    row.rowIndex = (currentPage.value - 1) * pagesize.value + rowIndex + 1;
  };

  const handleSizeChange = val => {
    pagesize.value = val;
  };
  const handleCurrentChange = val => {
    currentPage.value = val;
  };

  //当用户手动勾选数据行的 Checkbox 时触发的事件
  const select = (selection, row) => {
    selectRows.value = selection;
    emit('select', selection, row);
  };
  //当用户手动勾选全选 Checkbox 时触发的事件
  const selectAll = selection => {
    selectRows.value = selection;
    emit('select-all', selection);
  };
  //当选择项发生变化时会触发该事件
  const selectionChange = selection => {
    emit('selection-change', selection);
  };
  //当单元格 hover 进入时会触发该事件
  const cellMouseEnter = (row, column, cell, event) => {
    emit('cell-mouse-enter', row, column, cell, event);
  };
  //当单元格 hover 退出时会触发该事件
  const cellMouseLeave = (row, column, cell, event) => {
    emit('cell-mouse-leave', row, column, cell, event);
  };
  //当用户点击单元格时会触发该事件
  const cellClick = (row, column, cell, event) => {
    emit('cell-click', row, column, cell, event);
  };
  //当用户双击单元格时会触发该事件
  const cellDbclick = (row, column, cell, event) => {
    row[column.property + 'edit'] = true;

    emit('cell-dbclick', row, column, cell, event);
  };
  //当用户右击单元格时会触发该事件
  const cellContextmenu = (row, column, cell, event) => {
    emit('cell-contextmenu', row, column, cell, event);
  };
  //当用户点击行时会触发该事件
  const rowClick = (row, column, event) => {
    emit('row-click', row, column, event);
  };
  //当用户双击行时会触发该事件
  const rowDbclick = (row, column, event) => {
    emit('row-dbclick', row, column, event);
  };
  //当用户右击行时会触发该事件
  const rowContextmenu = (row, column, event) => {
    emit('row-contextmenu', row, column, event);
  };
  //当用户点击表头时会触发该事件
  const headerClick = (column, event) => {
    emit('header-click', column, event);
  };
  //当用户右击表头时会触发该事件
  const headerContextmenu = (column, event) => {
    emit('header-contextmenu', column, event);
  };
  //当表格的排序条件发生变化的时候会触发该事件
  const sortChange = (column, prop, order) => {
    emit('sort-change', column, prop, order);
  };
  //column 的 key， 如果需要使用 filter-change 事件，则需要此属性标识是哪个 column 的筛选条件
  const filterChange = filters => {
    emit('filter-change', filters);
  };
  //当表格的当前行发生变化的时候会触发该事件，如果要高亮当前行，请打开表格的 highlight-current-row 属性
  const currentChange = (currentRow, oldCurrentRow) => {
    emit('current-change', currentRow, oldCurrentRow);
  };
  //当拖动表头改变了列的宽度的时候会触发该事件
  const headerDragend = (newWidth, oldWidth, column, event) => {
    emit('header-dragend', newWidth, oldWidth, column, event);
  };
  //当用户对某一行展开或者关闭的时候会触发该事件（展开行时，回调的第二个参数为 expandedRows；树形表格时第二参数为 expanded）
  const expandChange = (row, expandedRows) => {
    emit('expand-change', row, expandedRows);
  };
  //删除某一行的时候会触发该事件
  const deleteRow = row => {
    tableData.value.data.splice(row.rowIndex - 1, 1);
  };
  //删除选中数据
  const deleteRows = () => {
    for (let i = selectRows.value.length; i > 0; i--) {
      tableData.value.data.splice(selectRows.value[i - 1].rowIndex - 1, 1);
    }
  };
  defineExpose({
    selectRows,
    select,
    deleteRows,
    deleteRow,
  });
</script>
<style lang="scss" scoped>
  .pageInfo {
    @extend .pageInfo;
  }
  .toolbar {
    @extend .toolbar;
  }
  .left-buttons {
    @extend .left-buttons;
  }
</style>
